package com.zyf.chapter01.refactor.practice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * 代码中可能存在的问题
 *   IdGenerator 是否可以设置成接口，如果项目中同时存在两个 ID 生成算法，那就需要抽象出来给更多系统使用
 *   generate 为静态函数，影响函数的可测试性
 *   代码实现依赖运行环境（本机名）、时间函数、随机函数，可测试性不好
 *   代码无注释，生成算法难懂
 *   魔法数较多
 *
 *  将代码重构分为四轮
 */
public class IdGenerator {
    private static final Logger logger = LoggerFactory.getLogger(IdGenerator.class);

    /**
     *
     * 打印结果示例：
     *      MM-202004241402-1609744246937-_AggxFIz
     *      MM-202004241402-1609744246939-gfHq\ey]
     *      MM-202004241402-1609744246939-VaqwzZeg
     *      MM-202004241402-1609744246939-_EbGFxgU
     * @return
     */
    public static String generate() {
        String id = "";

        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            String[] tokens = hostName.split("\\.");
            if (tokens.length > 0) {
                hostName = tokens[tokens.length - 1];
            }
            char[] randomChars = new char[8];
            int count = 0;
            Random random = new Random();
            while (count < 8) {
                int randomAscii = random.nextInt(122);
                if (randomAscii >= 48 && randomAscii <= 57) {
                    randomChars[count] = (char) ('0' + (randomAscii - 48));
                    count++;
                } else if (randomAscii >= 65 && randomAscii <= 95) {
                    randomChars[count] = (char) ('A' + (randomAscii - 65));
                    count++;
                } else if (randomAscii >= 95 && randomAscii <= 122) {
                    randomChars[count] = (char) ('a' + (randomAscii - 97));
                    count++;
                }
            }
            id = String.format("%s-%d-%s", hostName,
                    System.currentTimeMillis(), new String(randomChars));
        } catch (UnknownHostException e) {
            logger.warn("Failed to get the host name.");
        }
        return id;
    }
}
